//
//  UIImageViewExtension.swift
//

import Foundation
import Kingfisher

public extension UIImageView {
    func loadImage(_ url: String) {
        kf.setImage(with: URL(string: url)) { result in
            if case let .success(value) = result {
                self.image = value.image
            }
        }
    }
    
    func setImage(urlString: String,
                  placeholder: Placeholder? = nil,
                  options: KingfisherOptionsInfo? = nil,
                  progressBlock: DownloadProgressBlock? = nil,
                  completionHandler: ((UIImage?, Error?) -> Void)? = nil) {
        let encodedURLString = urlString.removingPercentEncoding?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let url = URL(string: encodedURLString ?? urlString)
        kf.setImage(with: url, placeholder: placeholder, options: options, progressBlock: progressBlock) { result in
            switch result {
            case let .success(value):
                completionHandler?(value.image, nil)
            case let .failure(error):
                completionHandler?(nil, error)
            }
        }
    }
}
